import {
    configureStore,
    createSlice,
} from "@reduxjs/toolkit";

// 商品模块
const goodsSlice = createSlice({
    name:"goods",
    initialState:{
        goodsList:[]
    },
    reducers:{
        // 添加商品
        addGoods(state,{payload}){
            state.goodsList.unshift({
                id:Math.random().toString(36).slice(2),
                ...payload
            })
        }
    }
})

const goods = goodsSlice.reducer;
// 购物车模块
const cartSlice = createSlice({
    name:"cart",
    initialState:{
        cartList:[],
    },
    reducers:{
        joinCart(state,{payload}){
            /*思路
            * 1- payload是商品信息，根据payload.i去购物车中查找是否有相同的元素
            *   1-1：有：buyNum+=1
            *   1-2: 无：为cartList增加一个元素
            */
           const info = state.cartList.find(v=>v.id===payload.id);
            if(info){
                // 有
                info.buyNum+=1;
            }else {
                // 无
                state.cartList.unshift({
                    ...payload,
                    buyNum:1
                })
            }
        }
    }
})

const cart = cartSlice.reducer;

// 创建store
const store = configureStore({
    reducer:{
        goods,
        cart
    }
})

// 获取actions
const {addGoods} = goodsSlice.actions;
const {joinCart} = cartSlice.actions;

// 操作数据
store.subscribe(function(){
    console.log(store.getState());
})

// 添加商品
store.dispatch(addGoods({goodsName:"笔记本",goodsPrice:1000}));
store.dispatch(addGoods({goodsName:"鼠标",goodsPrice:10}));

// 将商品放置到购物车
const {goodsList} = store.getState().goods;
store.dispatch(joinCart(goodsList[0]))
store.dispatch(joinCart(goodsList[1]))
store.dispatch(joinCart(goodsList[0]))
store.dispatch(joinCart(goodsList[0]))
